import 'package:dio/dio.dart';
import 'base_service.dart';
import '../models/user_model.dart';
import '../network/dio_client.dart';
import '../network/api_endpoints.dart';

class UserService extends BaseService {
  final Dio _dio = DioClient().dio;

  /// 获取用户列表
  Future<List<User>> getUsers() async {
    try {
      final response = await _dio.get(
        ApiEndpoints.getUsers,
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response);
      return extractData<List<User>>(response, (data) {
        return (data as List).map((e) => User.fromJson(e)).toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取用户列表错误: $e');
      throw '获取用户列表失败';
    }
  }

  /// 创建新用户
  Future<User> createUser(User user) async {
    try {
      // 生成新用户的ID（模拟服务器生成ID）
      final newUser = user.copyWith(id: DateTime.now().millisecondsSinceEpoch);

      final response = await _dio.post(
        ApiEndpoints.createUser,
        data: newUser.toJson(),
        options: Options(
          extra: {'logRequest': true, 'logResponse': true},
        ),
      );

      logResponse(response);

      // 在实际项目中，服务器会返回创建的用户对象
      return extractData<User>(response, (data) {
        return User.fromJson(data);
      });

      // 模拟服务器响应
      // return Future.delayed(Duration(seconds: 1), () => newUser);
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('创建用户错误: $e');
      throw '创建用户失败';
    }
  }

  /// 删除用户
  Future<bool> deleteUser(int id) async {
    try {
      final response = await _dio.delete(
        ApiEndpoints.getUser(id),
        options: Options(extra: {'logRequest': true}),
      );

      logResponse(response);

      // 在实际API中，成功删除通常返回204状态码
      if (response.statusCode == 200 || response.statusCode == 204) {
        return true;
      }
      return false;

      // 模拟删除成功
      // return Future.delayed(Duration(seconds: 1), () => true);
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('删除用户错误: $e');
      throw '删除用户失败';
    }
  }
  Future<User> getUser(user) async{
    try{
      final response = await _dio.get(
        ApiEndpoints.getUser(user.id),
      );
      return User.fromJson(response.data);
    }on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取用户错误: $e');
      throw '获取用户失败';
    }
  }


  /// 更新用户信息
  Future<User> updateUser(User user) async {
    try {
      final response = await _dio.put(
        ApiEndpoints.getUser(user.id),
        data: user.toJson(),
        options: Options(
          extra: {'logRequest': true, 'logResponse': true},
        ),
      );

      logResponse(response);
      return extractData<User>(response, (data) => User.fromJson(data));
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('更新用户错误: $e');
      throw '更新用户失败';
    }
  }
  /// 上传用户头像
  Future<String> uploadUserAvatar(int userId, String filePath) async {
    try {
      final formData = FormData.fromMap({
        'userId': userId,
        'file': await MultipartFile.fromFile(filePath, filename: 'avatar.jpg'),
      });

      final response = await _dio.post(
        ApiEndpoints.uploadFile,
        data: formData,
        options: Options(
          extra: {
            'logRequest': true,
            'logResponse': true,
            'ignoreBaseUrl': false,
          },
        ),
        onSendProgress: (sent, total) {
          if (total != -1) {
            logger.i('头像上传进度: ${(sent / total * 100).toStringAsFixed(1)}%');
          }
        },
      );

      logResponse(response); // 记录响应日志

      return extractData<String>(response, (data) {
        // 假设API返回格式: {"url": "https://example.com/avatar.jpg"}
        return data['url'] as String;
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('头像上传处理错误: $e');
      throw '头像上传处理失败';
    }
  }

  /// 搜索用户
  Future<List<User>> searchUsers(String query) async {
    try {
      final response = await _dio.get(
        ApiEndpoints.getUsers,
        queryParameters: {'q': query},
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response); // 记录响应日志

      return extractData<List<User>>(response, (data) {
        return (data as List)
            .map((userJson) => User.fromJson(userJson))
            .toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('用户搜索数据处理错误: $e');
      throw '用户搜索数据处理失败';
    }
  }

  Future<Response> uploadFile(String filePath) async {
    FormData formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(filePath),
    });
    return _dio.post(ApiEndpoints.uploadFile, data: formData,
        onSendProgress: (sent, total) {
          logger.i('上传进度: ${(sent / total * 100).toStringAsFixed(0)}%');
        });
  }
}
